package service

import (
	"com.cyt.yunpay/app/model"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/frame/g"
	"com.cyt.yunpay/library/response"
)

// 中间件管理服务
var Middleware = new(middlewareService)

type middlewareService struct{}

// 允许接口跨域请求
func (s *middlewareService) CORS(r *ghttp.Request) {
	r.Response.CORSDefault()
	r.Middleware.Next()
}

// authHook is the HOOK function implements JWT logistics.
func (s *middlewareService) JwtAuth(r *ghttp.Request) {
	Auth.MiddlewareFunc()(r)
	r.Middleware.Next()
}

// 自定义上下文对象
func (s *middlewareService) Ctx(r *ghttp.Request) {
	// 初始化，务必最开始执行
	customCtx := &model.Context{
	}
	Context.Init(r, customCtx)
	r.Middleware.Next()
}


// 处理panic产生的错误
func (s *middlewareService) Error(r *ghttp.Request) {
	r.Middleware.Next()
	if err := r.GetError(); err != nil {
		g.Log("exception").Error(err) // 记录到自定义错误日志文件
		r.Response.ClearBuffer()      //返回固定的友好信息
		response.JsonExit(r, 500, "服务器居然开小差了，请稍后再试吧！")
	}
}